import { Controller, Get, Param, Post, Body, Put, Delete, Query } from '@nestjs/common';
import { PostService } from './post.service';
import { User as UserModel, Post as PostModel } from '@prisma/client';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { PostData, QueryPost, UpdatePost } from './dto';

@Controller('post')
@ApiTags('帖子')
export class PostController {
  constructor(private readonly postService: PostService) { }

  @Get('posts')
  @ApiOperation({ summary: '查询所有帖子' })
  async getPosts(@Query() query: QueryPost) {
    const { page, pageSize } = query
    let skip = undefined
    let take = undefined
    if (page && pageSize) {
      skip = +page < 1 ? 0 : (page - 1) * pageSize
      take = +pageSize
    }
    return this.postService.posts(skip, take)
  }

  @Get('post/:id')
  @ApiOperation({ summary: '查询帖子' })
  async getPostById(@Param('id') id: string) {
    return this.postService.post({ id: +id })
  }

  @Post('post')
  @ApiOperation({ summary: '发布帖子' })
  async createDraft(@Body() postData: PostData) {
    const { title, content, authorEmail } = postData
    return this.postService.createPost({
      title,
      content,
      author: {
        connect: { email: authorEmail }
      }
    })
  }

  @Put('post')
  @ApiOperation({ summary: '修改' })
  async updatePost(@Body() data: UpdatePost) {
    const { id, title, content, publish } = data
    return this.postService.updatePost({ where: { id }, data: { title, content, publish: !!publish } })
  }

  @Delete('deletePost/:id')
  @ApiOperation({ summary: '删除帖子' })
  async deleteUser(@Param('id') id: number) {
    return this.postService.deletePost({ id: +id })
  }
}
